﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AbstraX;
using System.Linq.Expressions;
using System.Xml.Serialization;
using System.IO;
using AbstraX.ServerInterfaces;
using System.ServiceModel.DomainServices.Server;
using CodePlex.XPathParser;
using AbstraX.XPathBuilder;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Xml;

public static class AbstraXExtensions
{
    public static string MakeID(this IBase baseObject, string predicate)
    {
        var id = "/" + baseObject.GetType().Name + "[@" + predicate + "]";

        if (baseObject.Parent != null)
        {
            id = baseObject.Parent.ID + id;
        }

        return id;
    }

    public static string GetRootID(string id)
    {
        var regex = new Regex(@"/(?<providertype>\w+?)\[\@URL=\'(?<url>.*?)\'\]");

        if (regex.IsMatch(id))
        {
            var match = regex.Match(id);
            var rootID = "/" + match.Groups["providertype"].Value + "[@URL='" + match.Groups["url"].Value + "']";

            return rootID;
        }
        else
        {
            return null;
        }
    }

    public static IBase GenerateByID(this IAbstraXProviderService service, string id)
    {
        var queue = new Queue<string>();
        var parser = new XPathParser<string>();
        var builder = new XPathStringBuilder();

        parser.Parse(id, builder);

        var axisElement = builder.AxisElementQueue.Last();
        var method = service.GetType().GetMethods().Single(m => m.ReturnType.Name == "IQueryable`1" && m.GetParameters().Length == 0 && m.ReturnType.GetGenericArguments().Any(a => a.Name == axisElement.Element));
        var results = (IQueryable<IBase>) method.Invoke(service, null);

        return results.Where(b => b.ID == id).Single();
    }
}
